package com.example.ruijiproject.config;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSON;
import com.example.ruijiproject.common.BaseContext;
import com.example.ruijiproject.domain.Result;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;


@Slf4j
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;

        // 获取本次请求的URL
        String requestURI = request.getRequestURI();
        log.info("拦截到的URL：{}",request.getRequestURI());
        //定义不需要处理的请求
        String[] urls= new String[]{"/employee/login","/employee/logout","/backend/**","/front/**","/common/**"};
        // 判断本次请求是否需要处理
        boolean check = check(urls,requestURI);
        if(check){
            //不需要处理，放行
            log.info("本次请求：{}，不需要处理，放行",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        //判断是否已经登录，如果已经登录，放行
        if(request.getSession().getAttribute("employee")!=null){
            log.info("本次请求：{}，已经登录，放行",requestURI);
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }

        //如果没有登录，跳转到登录页面
        log.info("本次请求：{}，没有登录，跳转到登录页面",requestURI);
        log.info("用户id{}",request.getSession().getAttribute("employee"));
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
    }

    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match=PATH_MATCHER.match(url,requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
